<template>
  <div id="leave-listing" class="manage-pos">
    <tag-box v-show="showChild">
      <template v-slot:leave>
        <div class="opentype-tag choose-bg-tag">
          <template v-if="openType === 0 || openType === 1 ">请假申请单</template>
          <template v-if="openType === 2">请假详情单</template>
          <template v-if="openType === 3">流程审批进度历史</template>
        </div>
      </template>
    </tag-box>
    <div class="dep_top" v-show="!showChild">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="9" :sm="24">
              <a-form-item label="       标题" class="label-pre">
                <a-input
                  v-model="queryParam.title"
                  placeholder="请输入"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select
                  placeholder="请选择"
                  v-model="queryParam.status"
                  class="form-item-custom-select">
                  <a-select-option
                    v-for="(item) in statusList"
                    :key="item.id"
                    :value="item.item_val">
              <span style="display: inline-block;width: 100%"
                    :title=" item.item_desc">
                {{ item.item_desc}}
              </span>
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col  :md="7" :sm="24">
              <a-form-item label="结果">
                <a-select
                  v-model="queryParam.result"
                  placeholder="请选择">
                  <a-select-option
                    v-for="(item) in resultList"
                    :key="item.id"
                    :value="item.item_val">
                    <span style="display: inline-block;width: 100%"
                          :title=" item.item_desc">
                      {{ item.item_desc}}
                    </span>
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="48">
            <a-col :md="9" :sm="24">
              <a-form-item label="创建时间">
                <a-range-picker v-model="createTime" />
              </a-form-item>
            </a-col>
            <a-col  :md="8" :sm="24">
          <span class="table-edit-submitButtons">
            <a-button class="ml8" @click="queryApply">查询</a-button>
            <a-button type="primary" class="ml8" @click="handleReset">重置</a-button>
            <a-button type="danger" class="ml8" @click="applyProcess">发起申请</a-button>
          </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </div>
    <div class="dep_main" v-show="!showChild">
      <a-table
        :scroll="{x: 1300}"
        bordered
        ref="table"
        size="small"
        rowKey="id"
        :columns="columns"
        :data-source="listData"
        :pagination="paginationInfo"
        :loading="loading"
        @change="handleTableChange">
        <template slot="action" slot-scope="t,r,i">
          <template v-if="r.status == 1">
            <a href="javascript:void(0);" @click="lookHistory(r)" style="color:blue;">查看进度</a>
            <a-divider type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                更多 <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item key="1">
                  <a href="javascript:void(0);" style="color:#FFAD25;" @click="() => revokeLeave(r)">撤回</a>
                </a-menu-item>
                <a-menu-item key="2">
                  <a href="javascript:void(0);" @click="() => lookDetail(r)" style="color:#999;">详情</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
          <template v-else-if="(r.status == 2 && r.result == 3) || r.status == 3">
            <a href="javascript:void(0);" @click="editLeave(r)" style="color:#000000;">编辑</a>
            <a-divider type="vertical" />
            <a href="javascript:void(0);" @click="lookHistory(r)" style="color:blue;">查看进度</a>
          </template>
          <template v-else>
            <a href="javascript:void(0);" @click="lookDetail(r)" style="color:#999;">详情</a>
            <a-divider type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                更多 <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item key="1" v-if="r.status !== 2">
                  <a href="javascript:void(0);" @click="() => revokeLeave(r)" style="color:#FFAD25;">撤回</a>
                </a-menu-item>
                <a-menu-item key="2">
                  <a href="javascript:void(0);" @click="lookHistory(r)" style="color:blue;">审批历史</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </template>
      </a-table>
    </div>
    <transition name="slide-fade">
      <div class="popContainer" v-if="showChild">
        <edit-apply
          v-if="openType === 1 || openType === 0"
          :open-type="openType"
          :show-child.sync="showChild"
          :detail-info="detailInfo"
          :identity.sync="identity"
          @handleForm='handleForm'></edit-apply>

        <apply-detail
          v-if="openType === 2"
          :show-child.sync="showChild"
          :detail-info="detailInfo"
        ></apply-detail>

        <historic-detail
          v-if="openType === 3"
          :show-child.sync="showChild"
          :procInstId="procInstId"></historic-detail>
      </div>
    </transition>
    <a-modal
      title="流程信息预选"
      v-model="processVisible"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-select
        placeholder="Please select"
        style="width: 200px"
        :value="identity"
        @change="handleChange"
      >
        <a-select-option value="" key="0">请选择流程信息</a-select-option>
        <a-select-option value="type_leader" key="1">总经理审批</a-select-option>
        <a-select-option value="type_other" key="2">直属部门经理审批</a-select-option>
        <a-select-option value="type_developer" key="3">主管审批</a-select-option>
      </a-select>
    </a-modal>
    <a-modal
      title="确认撤回"
      :visible="reasonVisible"
      :confirm-loading="confirmLoading"
      @ok="revokeSubmit"
      @cancel="revokeCancel"
    >
      <a-input type="textarea" rows="4" placeholder="请输入撤销原因" v-model="revokeReason"></a-input>
    </a-modal>
  </div>
</template>
<script>
import { EditApply, ApplyDetail } from './modules/ApplyComp' // 弹窗
import { TagBox } from '@/myComponents'
import {applyList, saveProcessInfo, getAction, postFormAction, getApproveToDoList} from '@/api/process'
import HistoricDetail from '@/views/leaveManage/modules/HistoricDetail'
import { STable } from '@/components'
import moment from 'moment'
import 'moment/locale/zh-cn'
import {codeAll} from "@/api/leave";
export default {
  name: 'ApplyList',
  components: {
    EditApply,
    TagBox,
    STable,
    ApplyDetail,
    HistoricDetail
  },
  data () {
    return {
      processVisible: false,
      openType: 0,
      detailInfo: {},
      formData: {},
      isGateway: false,
      modalVisible: false,
      showAssign:false,
      error: '',
      assigneeList: [],
      submitLoading: false,
      pageType: '',
      showChild: false,
      showDetail: false,
      modalCancelVisible: false,
      columns: [
        {
          title: '#',
          width: 50,
          align: 'center',
          dataIndex: '',
          customRender: (t, r, index) => {
            return ((this.paginationInfo.current - 1) * this.paginationInfo.pageSize + index + 1)
          }
        },
        {
          title: '标题',
          width: 150,
          align: 'center',
          dataIndex: 'title'
        },
        {
          title: '所属流程',
          width: 150,
          align: 'center',
          dataIndex: 'processName'
        },
        {
          title: '当前审批环节',
          width: 150,
          dataIndex: 'currTaskName',
          align: 'center'
        },
        {
          title: '状态',
          width: 150,
          align: 'center',
          dataIndex: 'status',
          sorter: (a,b) => a.status - b.status,
          customRender: (t, r, index) => {
            return this.getStatus(t)
          }
        },
        {
          title: '结果',
          width: 150,
          dataIndex: 'result',
          align: 'center',
          sorter: (a,b) => a.result - b.result,
          customRender: (t, r, index) => {
            return this.getResult(t)
          }
        },
        {
          title: '创建时间',
          width: 150,
          dataIndex: 'createTime',
          align: "center",
          // sorter:true
        },
        {
          title: '提交申请时间',
          width: 150,
          dataIndex: 'applyTime',
          align: "center",
        },
        {
          title: '操作',
          width: 200,
          fixed: 'right',
          dataIndex: '',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      paginationInfo: {
        showSizeChanger: true,
        total: 0,
        current: 1,
        pageSizeOptions: ['5', '10', '15'],
        pageSize: 10,
        params: {}
      },
      tableData: [],
      listData: [],
      loading: false,
      url: {
        list: "/actBusiness/listData",
        getProcessDataList: "/activiti_process/listData",
        delByIds:'/actBusiness/delByIds',
        getFirstNode:'/actProcessIns/getFirstNode',
        applyBusiness:'/actBusiness/apply',
        cancelApply:'/actBusiness/cancel',
        detailInfo: '/actBusiness/getForm',
        editForm: '/actBusiness/editForm',
        saveForm: '/actBusiness/add'
      },
      cancelForm: {},
      procInstId: '',
      identity: '',
      currentApply: null,
      queryParam: {},
      createTime: [],
      statusList: [],
      resultList: [],
      reasonVisible: false,
      revokeReason: '',
      confirmLoading: false,
      revokeForm: null
    }
  },
  computed: {
    userInfo () {
      return this.$store.getters.userInfo
    }
  },
  created () {
    this.initList()
    this.getStatusAndResult()
  },
  mounted () {
    this.$store.dispatch('setLeaveTypes')
  },
  methods: {
    getStatus (item_val) {
      const statusList = this.statusList
      for (let i = 0; i < statusList.length; i++) {
        if (statusList[i]['item_val'] == item_val) {
          return statusList[i]['item_desc']
        }
      }
    },
    getResult (item_val) {
      const resultList = this.resultList
      for (let i = 0; i < resultList.length; i++) {
        if (resultList[i]['item_val'] == item_val) {
          return resultList[i]['item_desc']
        }
      }
    },
    // 申请单状态 和 审批结果
    getStatusAndResult () {
      // 请假申请单 状态
      let p1 = new Promise((resolve, reject) => {
        codeAll({item_type_id: '13'}).then((data) => {
          if (data.success) {
            resolve(data)
          } else {
            reject(data)
          }
        }, (error) => {
          resolve(error)
        })
      })
      // 申请单审批结果
      let p2 = new Promise((resolve, reject) => {
        codeAll({item_type_id: '14'}).then((data) => {
          if (data.success) {
            resolve(data)
          } else {
            reject(data)
          }
        }, (error) => {
          resolve(error)
        })
      })
      Promise.all([p1, p2]).then((res) => {
        console.log('p1p2', res)
        this.statusList = res[0].data
        this.resultList = res[1].data
      }).catch(error => {})
    },
    // 分页处理方法
    showDataLocal () {
      const tableData = this.tableData
      const num = this.paginationInfo.current
      const size = this.paginationInfo.pageSize
      this.listData = tableData.slice((num -1)*size, size*num)
    },
    handleTableChange (pagination, filters, sorter) {
      this.paginationInfo = pagination;
      this.showDataLocal()
    },
    async initList (loadType) {
      if (loadType === 'init') {
        this.paginationInfo.current = 1
        this.paginationInfo.params = {}
      }
      const params = {
        _t: parseInt(new Date().getTime() / 1000),
        column: 'createTime',
        order: 'desc',
        loginUserId: this.userInfo.id
      }
      this.loading = true
      const data = await applyList(Object.assign(params, this.paginationInfo.params))
      this.loading = false
      if (data.success) {
        this.paginationInfo.total = data.result.length
        this.tableData = data.result
        const listData = data.result.slice(0, this.paginationInfo.pageSize)
        this.listData = listData
      } else {
        this.$message.error(data.message)
      }
    },
    handleReset () {
      this.queryParam = {}
      this.createTime = []
      this.paginationInfo.params = {}
      this.initList('init')
    },
    queryApply () {
      console.log(this.createTime)
      if (this.createTime.length > 0) {
        this.queryParam.createTime_begin = this.createTime[0].format('YYYY-MM-DD')
        this.queryParam.createTime_end = this.createTime[1].format('YYYY-MM-DD')
      }
      this.paginationInfo.params = this.queryParam
      this.initList()
    },
    applyProcess () {
      this.openType = 0
      this.processVisible = true
    },
    /**
     * editType 0 新增 1 编辑
     * leaveParams 申请单数据
     * approveParams 审批相关信息
     * approveType 申请单保存 或 送批 save approve
     */
    async handleForm (openType, leaveParams, approveParams, approveType) {
      let _url = ''
      let params = {}
      _url = openType === 0 ? this.url.saveForm : this.url.editForm
      params = openType === 0 ? Object.assign(leaveParams, {loginUserId: this.userInfo.id}) : leaveParams
      const result = await postFormAction(_url, params)
      if (result.success) {
        if (openType === 0) {
          if (approveType === 'approve') {
            approveParams.id = result.message
            this.applySubmit(approveParams)
          } else {
            this.$message.success(result.message)
            this.initList('init')
          }
        } else if (openType === 1) {
          if (approveType === 'approve') {
            approveParams.id = this.procInstId
            this.applySubmit(approveParams)
          } else {
            this.$message.success(result.message)
            this.initList()
          }
        }
        this.showChild = false;
        this.identity = ''
      } else {
        this.$message.error(result.message)
      }
    },
    getDetailInfo (r) {
      const params = {
        _t: parseInt(new Date().getTime() / 1000),
        tableId: r.tableId,
        tableName: r.tableName,
        loginUserId: this.userInfo.id
      }
      getAction(this.url.detailInfo, params).then(res => {
          if (res.success) {
            this.detailInfo = res.result
            this.showChild = true
          }
      }).catch(error => {
        console.log(error)
      })
    },
    applySubmit(params) {
      this.submitLoading = true
      const pa2rams = Object.assign({},params, {loginUserId: this.userInfo.id});
      postFormAction(this.url.applyBusiness, pa2rams).then(res => {
        if (res.success) {
          this.$message.success("操作成功");
          this.initList('init')
        }else {
          this.$message.error(res.message)
        }
      }).finally(()=>this.submitLoading = false);
    },
    editLeave(r,isView) {
      console.log('applylist-edit', r)
      if (isView) {
        this.openType = 2 // 详情
        this.getDetailInfo(r)
      } else {
        this.openType = 1
        this.procInstId = r.id
        this.currentApply = r
        this.processVisible = true
      }
    },
    remove(r) {
      postFormAction(this.url.delByIds,{ids:r.id}).then((res)=>{
        if (res.success){
          this.$message.success(res.message)
          this.initList('init');
        }else {
          this.$message.error(res.message)
        }
      })
    },
    lookHistory(v) {
      if (!v.procInstId) {
        this.$message.error("流程实例ID不存在");
        return;
      }
      this.openType = 3
      this.procInstId = v.procInstId;
      this.showChild = true
    },
    lookDetail(v) {
      this.editLeave(v,true)
    },
    revokeSubmit () {
      const _this = this
      this.confirmLoading = true
      postFormAction(_this.url.cancelApply, {
        id: this.revokeForm.id,
        procInstId: this.revokeForm.procInstId,
        reason: this.revokeReason
      }).then(data => {
        if (data.success) {
          _this.$message.success(data.message)
          _this.initList('init')
        } else {
          _this.$message.error(data.message)
        }
      }).catch(error => {}).finally(() => {
        this.confirmLoading = false
        this.reasonVisible = false
        this.revokeForm = null
        this.revokeReason = null
      })
    },
    revokeCancel () {
      this.reasonVisible = false
    },
     revokeLeave(v) {
       let _this = this
       this.reasonVisible = true
       this.revokeForm = v
    },
    handleOk () {
      if (this.identity === '') {
        this.$message.warning('请选择流程信息')
      } else {
        this.processVisible = false
        if (this.openType === 1) {
          this.getDetailInfo(this.currentApply)
        } else {
          this.showChild = true
        }
      }
    },
    handleCancel () {
      this.identity = ''
    },
    handleChange (value) {
      this.identity = value
    }
  }
}
</script>

<style scoped>

</style>
